Branchwell

Lumen & Gesso / website · lumengesso.com / app / orders / [id] / review-form.tsx

1'use client';
2
3import { useState, type FormEvent } from 'react';
4import { REVIEW_COMMENT_LIMIT, REVIEW_DISCOVERY_SOURCE_LIMIT, REVIEW_DISCOVERY_SOURCES, REVIEW_DISPLAY_NAME_LIMIT, REVIEW_MAX_UPLOAD_BYTES } from '@/app/lib/reviews';
5
6async function resizePhoto(file: File): Promise<File> {
7 if (file.size <= REVIEW_MAX_UPLOAD_BYTES && ['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) return file;
8 const image = await createImageBitmap(file).catch(() => null);
9 if (!image) throw new Error('Please choose a JPG, PNG, or WebP photo.');
10 try {
11 const scale = Math.min(1, 1600 / Math.max(image.width, image.height));
12 const canvas = document.createElement('canvas');
13 canvas.width = Math.max(1, Math.round(image.width * scale));
14 canvas.height = Math.max(1, Math.round(image.height * scale));
15 const context = canvas.getContext('2d');
16 if (!context) throw new Error('Could not prepare your photo.');
17 context.fillStyle = '#fff';
18 context.fillRect(0, 0, canvas.width, canvas.height);
19 context.drawImage(image, 0, 0, canvas.width, canvas.height);
20 const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.84));
21 if (!blob || blob.size > REVIEW_MAX_UPLOAD_BYTES) throw new Error('Please choose a smaller photo.');
22 return new File([blob], 'review-photo.jpg', { type: 'image/jpeg' });
23 } finally {
24 image.close();
25 }
26}
27
28export function ReviewForm({ orderId }: { orderId: string }) {
29 const [rating, setRating] = useState(0);
30 const [discoverySource, setDiscoverySource] = useState('');
31 const [sending, setSending] = useState(false);
32 const [sent, setSent] = useState(false);
33 const [error, setError] = useState('');
34
35 const submit = async (event: FormEvent<HTMLFormElement>) => {
36 event.preventDefault();
37 if (sending) return;
38 const form = new FormData(event.currentTarget);
39 const photo = form.get('photo');
40 setSending(true);
41 setError('');
42 try {
43 if (photo instanceof File && photo.size) form.set('photo', await resizePhoto(photo));
44 const res = await fetch(`/api/orders/${orderId}/review`, { method: 'POST', body: form });
45 const result = await res.json().catch(() => null) as { error?: string } | null;
46 if (!res.ok) throw new Error(result?.error ?? 'Could not submit your review. Try again.');
47 setSent(true);
48 } catch (error) {
49 setError(error instanceof Error ? error.message : 'Could not submit your review. Try again.');
50 } finally {
51 setSending(false);
52 }
53 };
54
55 if (sent) return <p role="status">Thank you for sharing. Your review is with the studio for approval.</p>;
56
57 return (
58 <form className="order-review__form" onSubmit={submit}>
59 <fieldset className="order-review__rating" disabled={sending}>
60 <legend>Your rating</legend>
61 {[1, 2, 3, 4, 5].map(value => (
62 <label data-filled={value <= rating} key={value}>
63 <input type="radio" name="rating" value={value} checked={rating === value} onChange={() => setRating(value)} required aria-label={`${value} ${value === 1 ? 'star' : 'stars'}`} />
64 <span aria-hidden="true">{value <= rating ? '★' : '☆'}</span>
65 </label>
66 ))}
67 </fieldset>
68 <label>Your review
69 <textarea name="comment" className="auth__input" rows={4} required maxLength={REVIEW_COMMENT_LIMIT} disabled={sending} />
70 </label>
71 <label>Name to display (optional)
72 <input name="display_name" className="auth__input" maxLength={REVIEW_DISPLAY_NAME_LIMIT} disabled={sending} />
73 </label>
74 <label>Photo of your pet or portrait (optional)
75 <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" disabled={sending} />
76 </label>
77 <div>
78 <label>How did you hear about Lumen &amp; Gesso? (optional)
79 <select name="discovery_source" className="auth__input" value={discoverySource} onChange={e => setDiscoverySource(e.target.value)} disabled={sending} aria-describedby="review-discovery-privacy">
80 <option value="">Select an option</option>
81 {REVIEW_DISCOVERY_SOURCES.map(source => <option key={source}>{source}</option>)}
82 </select>
83 </label>
84 <span id="review-discovery-privacy" className="approve__hint">Only the studio sees this answer.</span>
85 </div>
86 {discoverySource === 'Other' && (
87 <label>Where did you hear about us?
88 <input name="discovery_other" className="auth__input" maxLength={REVIEW_DISCOVERY_SOURCE_LIMIT} required disabled={sending} />
89 </label>
90 )}
91 <label className="approve__checkbox">
92 <input type="checkbox" name="permission" required disabled={sending} />
93 <span>Lumen &amp; Gesso may display my review and any photo I submit on its website.</span>
94 </label>
95 {error && <p role="alert" className="auth__error">{error}</p>}
96 <button className="btn btn--rose btn--md" disabled={sending} type="submit">{sending ? 'Submitting…' : 'Submit review'}</button>
97 </form>
98 );
99}